package com.association.main.controller;
import com.association.main.common.CustomException;
import com.association.main.common.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.jodconverter.DocumentConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {
    @Value("${image_path}")
    private String basePath;

    @Value("${docPath}")
    private String docPath;
    @Value("${pdfPath}")
    private String pdfPath;
    @Autowired
    private DocumentConverter converter;  //用于转换
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file){
        //file这是一个临时文件是tomcat的效果
        String originalFilename = file.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        //获取后缀
        String fileName = UUID.randomUUID().toString() +substring;
        File dir=new File(basePath);
        //判断文件路径是否存在
        if(!dir.exists()){
            dir.mkdirs();
        }
        try {
            //转存到指定位置
            file.transferTo(new File(basePath+fileName));
        } catch (IOException e) {
           throw new CustomException("上传失败了");
        }

        log.info(file.toString());
        return R.success(fileName);
    }

    @GetMapping("/download")
    public void download(String name, HttpServletResponse rsp){
        //输入流，通过输入流读取文件
        try {
            FileInputStream fileInputStream=new FileInputStream(basePath+name);
            ServletOutputStream outputStream=rsp.getOutputStream();

            rsp.setContentType("image/jpeg");
            int len=0;
            byte[] bytes=new byte[1024];
            while ((len=fileInputStream.read(bytes))!=-1){
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }
            outputStream.close();
            fileInputStream.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
        //输出流，通过输出流写回浏览器
    }

    @GetMapping("/pdf")
    public void toPdfFile(HttpServletResponse response,String doc) {
        response.setContentType("application/pdf;charset=utf-8");
        File file = new File(docPath+doc);//需要转换的文件
        try {
            File newFile = new File(pdfPath);//转换之后文件生成的地址
            if (!newFile.exists()) {
                newFile.mkdirs();
            }
           //pdf文件生成保存的路径
            String fileName="JCccc"+UUID.randomUUID().toString().replaceAll("-","").substring(0,6);
            String fileType=".pdf"; //pdf文件后缀
            String newFileMix=pdfPath+fileName+fileType;  //将这三个拼接起来,就是我们最后生成文件保存的完整访问路径了

            //文件转化
            converter.convert(file).to(new File(newFileMix)).execute();
            //使用response,将pdf文件以流的方式发送的前端浏览器上
            ServletOutputStream outputStream = response.getOutputStream();
            InputStream in = new FileInputStream(new File(newFileMix));// 读取文件
            int i = IOUtils.copy(in, outputStream);   // copy流数据,i为字节数
            in.close();
            outputStream.close();
            System.out.println("流已关闭,可预览,该文件字节大小："+i);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
